/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024. All rights reserved.
 *
 */
import { expect } from '@jest/globals';
import fse from 'fs-extra';
import path from 'path';

import { runHvigorAsync } from '../../common/common';
import { commonJson5Operation } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.StaticLibrary]
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();
  const module = project.getModule('staticLibrary');
  const modulePath = module.moduleRootPath();
  const commands1: string[] = '--mode module -p product=default -p module=staticLibrary@default assembleHar'.split(' ');
  const outputRoot = path.resolve(modulePath, 'BuildProfile.ets');

  const result1 = await runHvigorAsync(projectRootPath, commands1);
  record.addStep('首次构建，CreateHarBuildProfile为Finished', result1);
  expect(result1.stdout).toContain('BUILD SUCCESSFUL');
  expect(result1.stdout).toContain('Finished :staticLibrary:default@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);

  const result2 = await runHvigorAsync(projectRootPath, commands1);
  record.addStep('不做任何更改，再次构建，CreateHarBuildProfile为UP-TO-DATE', result2);
  expect(result2.stdout).toContain('BUILD SUCCESSFUL');
  expect(result2.stdout).toContain('UP-TO-DATE :staticLibrary:default@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);

  fse.removeSync(outputRoot);
  const result3 = await runHvigorAsync(projectRootPath, commands1);
  record.addStep('删除产物，再次构建，CreateHarBuildProfile为Finished', result3);
  expect(result3.stdout).toContain('BUILD SUCCESSFUL');
  expect(result3.stdout).toContain('Finished :staticLibrary:default@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);

  // 修改app.json5
  await commonJson5Operation(path.resolve(projectRootPath, 'AppScope/app.json5'), json => {
    json.app = {
      bundleName: json.app.bundleName + 1,
      vendor: json.app.vendor + 1,
      versionCode: json.app.versionCode + 1,
      versionName: json.app.versionName + 1,
      icon: json.app.icon,
      label: json.app.label
    }
    return json;
  });
  const result4 = await runHvigorAsync(projectRootPath, commands1);
  record.addStep('修改app.json5，再次构建，CreateHarBuildProfile为Finished', result4);
  expect(result4.stdout).toContain('BUILD SUCCESSFUL');
  expect(result4.stdout).toContain('Finished :staticLibrary:default@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);

  // 修改build-profile.json5-buildProfileFields
  await commonJson5Operation(path.resolve(modulePath, 'build-profile.json5'), json5 => {
    json5.apiType = json5.apiType || '';
    json5.buildOption = json5.buildOption || {};
    json5.buildOption.arkOptions = json5.buildOption.arkOptions || {};
    json5.buildOption.arkOptions.buildProfileFields = {"aaa": false};
    json5.buildOptionSet = json5.buildOptionSet || [];
    json5.targets = [{ 'name': 'default'}, { 'name': 'ohosTest'}, { 'name': 'target1'}];
    return json5;
  });
  const result5 = await runHvigorAsync(projectRootPath, commands1);
  record.addStep('修改build-profile.json5-buildProfileFields，再次构建，CreateHarBuildProfile为Finished', result5);
  expect(result5.stdout).toContain('BUILD SUCCESSFUL');
  expect(result5.stdout).toContain('Finished :staticLibrary:default@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);

  // 修改oh-package.json5-version 1.0.0 -> 1.0.1
  await commonJson5Operation(path.resolve(modulePath, 'oh-package.json5'), json5 => {
    json5.name = json5.name || '';
    json5.version = '1.0.1';
    json5.description = json5.description || '';
    json5.main = json5.main || '';
    json5.author = json5.author || '';
    json5.license = json5.license || '';
    json5.dependencies = json5.dependencies || {};
    return json5;
  });
  const result6 = await runHvigorAsync(projectRootPath, commands1);
  record.addStep('修改oh-package.json5-version，再次构建，CreateHarBuildProfile为Finished', result6);
  expect(result6.stdout).toContain('BUILD SUCCESSFUL');
  expect(result6.stdout).toContain('Finished :staticLibrary:default@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);

  // 修改buildMode--release
  const commands2: string[] = '--mode module -p product=default -p module=staticLibrary@default -p buildMode=release assembleHar'.split(' ');
  const result7 = await runHvigorAsync(projectRootPath, commands2);
  record.addStep('修改buildMode为release，再次构建，CreateHarBuildProfile为Finished', result7);
  expect(result7.stdout).toContain('BUILD SUCCESSFUL');
  expect(result7.stdout).toContain('Finished :staticLibrary:default@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);

  // 修改构建target--target1
  const commands3: string[] = '--mode module -p product=default -p module=staticLibrary@target1 -p buildMode=release assembleHar'.split(' ');
  const result8 = await runHvigorAsync(projectRootPath, commands3);
  record.addStep('修改构建target为target1，再次构建，CreateHarBuildProfile为Finished', result8);
  expect(result8.stdout).toContain('BUILD SUCCESSFUL');
  expect(result8.stdout).toContain('Finished :staticLibrary:target1@CreateHarBuildProfile');
  expect(fse.existsSync(outputRoot)).toEqual(true);
};

TestCaseBuilder.builder()
  .caseName('CreateHarBuildProfile')
  .description('CreateHarBuildProfile任务增量测试用例')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).build())
  .testFun(testFun)
  .load();
